package com.crawler.search.index.suffix;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONObject;
import com.crawler.search.utils.DateParseUtil;
import com.crawler.search.utils.DateUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * 根据类型，返回不同的索引类名
 * @author zyh
 *
 */
@Data
@AllArgsConstructor
public class DateSuffixer extends Suffixer {

	public String field;

	@Override
	public String getAliasIndex(String index) {
		return index.replaceAll("_[0-9]*$", "");
	}

	@Override
	public String createAliasName(JSONObject json) {
		return getDateSuffix(json);
	}

	/**
	* 
	* 根据日期设置索引别名后缀
	* @return {@link String}
	**/
	public  String getDateSuffix(JSONObject json){

		String suffix = DateUtils.getMonthYear(new Date());
		Date parseDate=null;
		String dateStr=null;

		if(!StringUtils.isEmpty(field)){

			if(json.containsKey(field)){
				dateStr=json.getString(field);
			}

			if(!StringUtils.isEmpty(dateStr)){
				try {
					Calendar cal=Calendar.getInstance();
					cal.add(Calendar.YEAR, -30);
					Date tryParseDate = DateParseUtil.tryParseDate(dateStr);
					long time = tryParseDate.getTime();
					long timeInMillis = cal.getTime().getTime();
					if(time>timeInMillis){
						parseDate=tryParseDate;
					}
				} catch (Exception e) {
					parseDate=new Date();
				}
			}
		}
		if(parseDate!=null){
			suffix= DateUtils.getMonthYear(parseDate);
			suffix="_"+suffix;
		}
		return suffix;
	}
}
